package com.weiquan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiquan.dto.CommentRequest;
import com.weiquan.dto.PostPublishRequest;
import com.weiquan.entity.CommunityComment;
import com.weiquan.entity.CommunityPost;
import com.weiquan.exception.BusinessException;
import com.weiquan.mapper.CommunityCommentMapper;
import com.weiquan.mapper.CommunityPostMapper;
import com.weiquan.service.CommunityService;
import com.weiquan.utils.RedisUtils;
import com.weiquan.vo.CommentVO;
import com.weiquan.vo.PostVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 社区服务实现类
 */
@Slf4j
@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityPostMapper, CommunityPost> implements CommunityService {

    @Autowired
    private CommunityPostMapper postMapper;

    @Autowired
    private CommunityCommentMapper commentMapper;

    @Autowired
    private RedisUtils redisUtils;

    // 分类映射
    private static final Map<Integer, String> CATEGORY_MAP = new HashMap<>();
    static {
        CATEGORY_MAP.put(1, "职场纠纷");
        CATEGORY_MAP.put(2, "消费维权");
        CATEGORY_MAP.put(3, "租房矛盾");
        CATEGORY_MAP.put(4, "其他");
    }

    // 状态映射
    private static final Map<Integer, String> STATUS_MAP = new HashMap<>();
    static {
        STATUS_MAP.put(0, "待解决");
        STATUS_MAP.put(1, "已解决");
        STATUS_MAP.put(2, "进行中");
    }

    @Override
    @Transactional
    public Long publishPost(PostPublishRequest request, Long userId) {
        // 创建帖子实体
        CommunityPost post = new CommunityPost();
        BeanUtils.copyProperties(request, post);
        post.setUserId(userId);
        
        // 处理Boolean到Integer的转换
        post.setIsAnonymous(request.getIsAnonymous() ? 1 : 0);
        
        post.setLikeCount(0);
        post.setCommentCount(0);
        post.setViewCount(0);
        post.setIsTop(0);
        post.setIsFeatured(0);
        post.setAuditStatus(1); // 暂时自动通过审核
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());

        // 保存帖子
        if (postMapper.insert(post) <= 0) {
            throw new BusinessException("发布帖子失败");
        }

        log.info("用户{}发布帖子成功，帖子ID：{}", userId, post.getId());
        return post.getId();
    }

    @Override
    public IPage<PostVO> getPostList(Integer current, Integer size, Integer categoryId, Integer status, String sortBy, String keyword, Long userId) {
        Page<CommunityPost> pageParam = new Page<>(current, size);
        
        // 构建查询条件
        QueryWrapper<CommunityPost> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted", 0);
        wrapper.eq("audit_status", 1); // 只显示审核通过的帖子
        
        // 分类筛选
        if (categoryId != null) {
            wrapper.eq("category", categoryId);
        }
        
        // 状态筛选
        if (status != null) {
            wrapper.eq("status", status);
        }
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("title", keyword).or().like("content", keyword));
        }
        
        // 排序
        if ("hot".equals(sortBy)) {
            wrapper.orderByDesc("comment_count", "like_count");
        } else if ("like".equals(sortBy)) {
            wrapper.orderByDesc("like_count");
        } else {
            wrapper.orderByDesc("create_time");
        }
        
        IPage<CommunityPost> postPage = postMapper.selectPage(pageParam, wrapper);

        // 转换为VO
        IPage<PostVO> result = new Page<>();
        BeanUtils.copyProperties(postPage, result);
        
        List<PostVO> postVOList = postPage.getRecords().stream()
                .map(post -> convertToPostVO(post, userId))
                .collect(Collectors.toList());
        
        result.setRecords(postVOList);
        return result;
    }

    @Override
    public PostVO getPostDetail(Long postId, Long userId) {
        // 获取帖子信息
        CommunityPost post = postMapper.selectById(postId);
        if (post == null || post.getIsDeleted() == 1) {
            throw new BusinessException("帖子不存在");
        }

        // 增加浏览数
        postMapper.increaseViewCount(postId);

        // 转换为VO
        PostVO postVO = convertToPostVO(post, userId);

        // 获取评论列表
        List<CommentVO> comments = getCommentList(postId, userId);
        postVO.setComments(comments);

        return postVO;
    }

    @Override
    public List<PostVO> getHotPosts(Integer limit) {
        List<CommunityPost> posts = postMapper.selectHotPosts(limit);
        return posts.stream()
                .map(post -> convertToPostVO(post, null))
                .collect(Collectors.toList());
    }

    @Override
    public List<PostVO> getFeaturedCases(Integer limit) {
        List<CommunityPost> posts = postMapper.selectFeaturedCases(limit);
        return posts.stream()
                .map(post -> convertToPostVO(post, null))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Boolean togglePostLike(Long postId, Long userId) {
        String likeKey = "post_like:" + postId + ":" + userId;
        
        if (redisUtils.hasKey(likeKey)) {
            // 取消点赞
            redisUtils.del(likeKey);
            postMapper.decreaseLikeCount(postId);
            return false;
        } else {
            // 点赞
            redisUtils.set(likeKey, "1", 86400 * 30); // 30天过期
            postMapper.increaseLikeCount(postId);
            return true;
        }
    }

    @Override
    @Transactional
    public Boolean togglePostCollect(Long postId, Long userId) {
        String collectKey = "post_collect:" + postId + ":" + userId;
        
        if (redisUtils.hasKey(collectKey)) {
            // 取消收藏
            redisUtils.del(collectKey);
            return false;
        } else {
            // 收藏
            redisUtils.set(collectKey, "1", 86400 * 365); // 1年过期
            return true;
        }
    }

    @Override
    @Transactional
    public Long publishComment(CommentRequest request, Long userId) {
        // 检查帖子是否存在
        CommunityPost post = postMapper.selectById(request.getPostId());
        if (post == null || post.getIsDeleted() == 1) {
            throw new BusinessException("帖子不存在");
        }

        // 创建评论实体
        CommunityComment comment = new CommunityComment();
        BeanUtils.copyProperties(request, comment);
        comment.setUserId(userId);
        comment.setLikeCount(0);
        comment.setAuditStatus(1); // 暂时自动通过审核
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());

        // 保存评论
        if (commentMapper.insert(comment) <= 0) {
            throw new BusinessException("发表评论失败");
        }

        // 更新帖子评论数
        postMapper.updateCommentCount(request.getPostId());

        log.info("用户{}发表评论成功，评论ID：{}", userId, comment.getId());
        return comment.getId();
    }

    @Override
    public List<CommentVO> getCommentList(Long postId, Long userId) {
        List<CommunityComment> comments = commentMapper.selectCommentsByPostId(postId);
        
        return comments.stream()
                .filter(comment -> comment.getParentId() == null) // 只获取顶级评论
                .map(comment -> {
                    CommentVO commentVO = convertToCommentVO(comment, userId);
                    
                    // 获取回复列表
                    List<CommunityComment> replies = commentMapper.selectRepliesByParentId(comment.getId());
                    List<CommentVO> replyVOList = replies.stream()
                            .map(reply -> convertToCommentVO(reply, userId))
                            .collect(Collectors.toList());
                    
                    commentVO.setReplies(replyVOList);
                    commentVO.setReplyCount(replyVOList.size());
                    
                    return commentVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Boolean toggleCommentLike(Long commentId, Long userId) {
        String likeKey = "comment_like:" + commentId + ":" + userId;
        
        if (redisUtils.hasKey(likeKey)) {
            // 取消点赞
            redisUtils.del(likeKey);
            commentMapper.decreaseLikeCount(commentId);
            return false;
        } else {
            // 点赞
            redisUtils.set(likeKey, "1", 86400 * 30); // 30天过期
            commentMapper.increaseLikeCount(commentId);
            return true;
        }
    }

    @Override
    @Transactional
    public Boolean deletePost(Long postId, Long userId) {
        CommunityPost post = postMapper.selectById(postId);
        if (post == null || post.getIsDeleted() == 1) {
            throw new BusinessException("帖子不存在");
        }
        
        if (!post.getUserId().equals(userId)) {
            throw new BusinessException("只能删除自己的帖子");
        }

        post.setIsDeleted(1);
        post.setUpdateTime(LocalDateTime.now());
        
        return postMapper.updateById(post) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteComment(Long commentId, Long userId) {
        CommunityComment comment = commentMapper.selectById(commentId);
        if (comment == null || comment.getIsDeleted() == 1) {
            throw new BusinessException("评论不存在");
        }
        
        if (!comment.getUserId().equals(userId)) {
            throw new BusinessException("只能删除自己的评论");
        }

        comment.setIsDeleted(1);
        comment.setUpdateTime(LocalDateTime.now());
        
        boolean result = commentMapper.updateById(comment) > 0;
        
        if (result) {
            // 更新帖子评论数
            postMapper.updateCommentCount(comment.getPostId());
        }
        
        return result;
    }

    @Override
    public List<PostVO> getUserPosts(Long userId) {
        List<CommunityPost> posts = postMapper.selectByUserId(userId);
        return posts.stream()
                .map(post -> convertToPostVO(post, userId))
                .collect(Collectors.toList());
    }

    @Override
    public List<CommentVO> getUserComments(Long userId) {
        List<CommunityComment> comments = commentMapper.selectByUserId(userId);
        return comments.stream()
                .map(comment -> convertToCommentVO(comment, userId))
                .collect(Collectors.toList());
    }

    @Override
    public IPage<PostVO> searchPosts(String keyword, Integer page, Integer size, Long userId) {
        return getPostList(page, size, null, null, null, keyword, userId);
    }

    @Override
    public List<Object> getCategoryStats() {
        return postMapper.selectCategoryStats();
    }

    /**
     * 转换帖子实体为VO
     */
    private PostVO convertToPostVO(CommunityPost post, Long userId) {
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        
        // 设置分类名称
        postVO.setCategoryName(CATEGORY_MAP.get(post.getCategory()));
        
        // 设置状态名称
        postVO.setStatusName(STATUS_MAP.get(post.getStatus()));
        
        // 处理标签
        if (StringUtils.hasText(post.getTags())) {
            postVO.setTagList(Arrays.asList(post.getTags().split(",")));
        }
        
        // 设置相对时间
        postVO.setRelativeTime(getRelativeTime(post.getCreateTime()));
        
        // 匿名处理
        if (post.getIsAnonymous() == 1) {
            postVO.setNickname("匿名用户");
            postVO.setAvatar(null);
        }
        
        // 设置用户交互状态
        if (userId != null) {
            String likeKey = "post_like:" + post.getId() + ":" + userId;
            String collectKey = "post_collect:" + post.getId() + ":" + userId;
            postVO.setIsLiked(redisUtils.hasKey(likeKey));
            postVO.setIsCollected(redisUtils.hasKey(collectKey));
        }
        
        return postVO;
    }

    /**
     * 转换评论实体为VO
     */
    private CommentVO convertToCommentVO(CommunityComment comment, Long userId) {
        CommentVO commentVO = new CommentVO();
        BeanUtils.copyProperties(comment, commentVO);
        
        // 设置相对时间
        commentVO.setRelativeTime(getRelativeTime(comment.getCreateTime()));
        
        // 匿名处理
        if (comment.getIsAnonymous() == 1) {
            commentVO.setNickname("匿名用户");
            commentVO.setAvatar(null);
        }
        
        // 设置用户交互状态
        if (userId != null) {
            String likeKey = "comment_like:" + comment.getId() + ":" + userId;
            commentVO.setIsLiked(redisUtils.hasKey(likeKey));
        }
        
        return commentVO;
    }

    /**
     * 获取相对时间
     */
    private String getRelativeTime(LocalDateTime dateTime) {
        LocalDateTime now = LocalDateTime.now();
        long minutes = ChronoUnit.MINUTES.between(dateTime, now);
        
        if (minutes < 1) {
            return "刚刚";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (minutes < 1440) { // 24小时
            return (minutes / 60) + "小时前";
        } else if (minutes < 10080) { // 7天
            return (minutes / 1440) + "天前";
        } else {
            return dateTime.format(DateTimeFormatter.ofPattern("MM-dd"));
        }
    }
}